
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include<linux/input.h>
#include <signal.h>




/*
 * ./ts_test /dev/input/event1
 */

int fd;

void my_sighandler_t(int sig)
{
	ssize_t readlen;
	int len = sizeof(struct input_event);
	struct input_event ev;
    while(1)
    {
	    readlen = read(fd, &ev, len);
		if(len == readlen)
		{
		  printf("Get : type = 0x%3x, code = 0x%3x, value = %d \n",ev.type, ev.code, ev.value);
		}
		else
		{
		  break;
		}
   }
}



//异步通知方式
int main(int argc, char** argv)
{
    
	int flags;

    if(argc != 2)
	{
	    printf("Usage:%s <dev>\n",argv[0]);
		return -1;
	}
	
    //打开设备
    fd = open(argv[1], O_NONBLOCK|O_RDWR);//非阻塞方式：CPU利用率高
    //fd = open(argv[1], O_RDWR);  //阻塞方式
	if(fd == -1)
	{
	    printf("%s open error\n",argv[1]);
		return -1;
	}

	/* 注册信号处理函数，设置收到信号做什么 */
    signal(SIGIO, my_sighandler_t);

	/* 把进程 ID 告诉驱动，F_SETOWN设置拥有者 */
	fcntl(fd, F_SETOWN, getpid());

    /* 使能驱动的 FASYNC 功能 */
    flags = fcntl(fd, F_GETFL);
    fcntl(fd, F_SETFL, flags | FASYNC);

	
    
    while(1)
    {
        printf("read book\n");
		sleep(10);
    }
   return 0;
}
